/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ThemeView.java
 *
 * Created on 27.05.2013, 20:00:32
 */
package db21;

import db21.entities.Competences;
import db21.entities.Entities;
import db21.entities.Subjects;
import db21.entities.Theme;
import db21.entities.Themes;
import db21.listeners.ClickOnlyListener;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JOptionPane;

/**
 *
 * @author Mamontov
 */
public class ThemeView extends ApplicationPanel {

    Theme m_theme;
    
    public Theme newTheme() {
        if (txtName.getText().isEmpty() 
            || cmbSubject.getSelectedIndex() < 0
            || (chkHasParent.isSelected() && cmbParentTheme.getSelectedIndex() < 0)) 
            return null;
        Theme t = new Theme();
        t.name = txtName.getText();
        t.hasParentTheme = chkHasParent.isSelected();
        if (t.hasParentTheme == true) {
            t.parentTheme = cmbParentTheme.getSelectedItem().toString();
        }
        t.subject = cmbSubject.getSelectedItem().toString();
        t.competences = Entities.selectedItemsToEntities(lstCompetences);
        
        return t;
    }
    
    /** Creates new form ThemeView */
    public ThemeView() {
        initComponents();
        JButton btns[] = {btnToCompetences, btnToSubjects,  btnToMain };
        ApplicationMode modes[] = { 
            ApplicationMode.Competences,
            ApplicationMode.Subjects,
            ApplicationMode.MainForm
        };
        for(int i = 0; i < btns.length; i++) {
            this.bindOnClickListenerTogglingToMode(btns[i], modes[i]);
        }
        JList lists[] = { 
            lstAllThemes, lstCompetences
        };
        for(int i = 0 ; i < lists.length; i++) {
            DefaultListModel m = new DefaultListModel();
            lists[i].setModel(m);
        }
        
        bindSave(btnSave);
        
        btnDelete.addMouseListener(new ClickOnlyListener() {

            @Override
            public void mouseClicked(MouseEvent e) {
                JList c = ThemeView.this.lstAllThemes;
                DefaultListModel k = (DefaultListModel)(ThemeView.this.lstAllThemes.getModel());
                int si = c.getSelectedIndex();
                if (si != -1) {
                    String o = c.getSelectedValue().toString();
                    ThemeView.this.m_model.resource(Themes.class).removeIndividual(o);
                    int index = Entities.findComboBoxItem(ThemeView.this.cmbParentTheme, o);
                    ThemeView.this.cmbParentTheme.removeItemAt(index);
                    k.remove(si);
                    if (si < k.size()) {
                        c.setSelectedIndex(si);
                    }
                }
            }
        });
        
        btnAdd.addMouseListener(new ClickOnlyListener() {

            @Override
            public void mouseClicked(MouseEvent e) {
                Theme t = ThemeView.this.newTheme();
                boolean ok = t!=null;
                if (ok) {
                    DefaultListModel k = (DefaultListModel)(ThemeView.this.lstAllThemes.getModel());
                    boolean result = m_model.resource(Themes.class).add(t);
                    if (result) {
                        k.addElement(t.name);
                        ThemeView.this.cmbParentTheme.addItem(t.name);
                    } else {
                         JOptionPane.showMessageDialog(ThemeView.this, "Individual already exists");
                    }
                }
                else {
                    JOptionPane.showMessageDialog(ThemeView.this, "Please fill name, subject and parentTheme if required");
                }
                        
            }
        });
    }
    
    
    public void updateWidgetsDueAChangedSelection() {
        if (m_theme != null) {
            txtName.setText(m_theme.name);
            chkHasParent.setSelected(m_theme.hasParentTheme);
            if (m_theme.hasParentTheme) {
                int index = Entities.findComboBoxItem(cmbParentTheme, m_theme.parentTheme);
                cmbParentTheme.setSelectedIndex(index);
            }
            if (m_theme.subject != null) {
                int index = Entities.findComboBoxItem(cmbSubject, m_theme.subject);
                cmbSubject.setSelectedIndex(index);
            }
            Entities.setSelectedValues(lstCompetences, m_theme.competences);
        }
    }
    
    @Override
    public void fireModelUpdate() {
        ArrayList<String> themes = this.m_model.resource(Themes.class).getList();
        Entities.populateComboBoxWithStrings(cmbParentTheme, themes);
        Entities.populateListWithStrings(lstAllThemes, themes);
        
        ArrayList<String> subjects = this.m_model.resource(Subjects.class).getList();
        Entities.populateComboBoxWithStrings(cmbSubject, subjects);
        
        ArrayList<String> competences = this.m_model.resource(Competences.class).getList();
        Entities.populateListWithStrings(lstCompetences, competences);
        
        lstAllThemesValueChanged(null);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        lstAllThemes = new javax.swing.JList();
        txtName = new javax.swing.JTextField();
        btnDelete = new javax.swing.JButton();
        btnAdd = new javax.swing.JButton();
        lblName = new javax.swing.JLabel();
        btnToCompetences = new javax.swing.JButton();
        btnToSubjects = new javax.swing.JButton();
        btnToMain = new javax.swing.JButton();
        chkHasParent = new javax.swing.JCheckBox();
        cmbParentTheme = new javax.swing.JComboBox();
        lblSubject = new javax.swing.JLabel();
        cmbSubject = new javax.swing.JComboBox();
        lblCompetences = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        lstCompetences = new javax.swing.JList();
        btnSave = new javax.swing.JButton();

        lstAllThemes.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        lstAllThemes.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                lstAllThemesValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(lstAllThemes);

        btnDelete.setText("Удалить");
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteActionPerformed(evt);
            }
        });

        btnAdd.setText("Добавить");

        lblName.setText("Название");

        btnToCompetences.setText("К компетенциям");

        btnToSubjects.setText("К предметам");

        btnToMain.setText("К главному окну");

        chkHasParent.setText("Имеет родителя");
        chkHasParent.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkHasParentActionPerformed(evt);
            }
        });

        lblSubject.setText("Относится к предмету");

        lblCompetences.setText("Обучает компетенциям");

        jScrollPane2.setViewportView(lstCompetences);

        btnSave.setText("Сохранить");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnAdd)
                        .addGap(18, 18, 18)
                        .addComponent(btnSave, javax.swing.GroupLayout.DEFAULT_SIZE, 89, Short.MAX_VALUE)
                        .addGap(16, 16, 16)
                        .addComponent(btnDelete))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 283, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(btnToCompetences)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnToSubjects)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnToMain))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 333, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(lblSubject)
                                    .addComponent(chkHasParent)
                                    .addComponent(lblName))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(cmbSubject, 0, 200, Short.MAX_VALUE)
                                    .addComponent(cmbParentTheme, 0, 200, Short.MAX_VALUE)
                                    .addComponent(txtName, javax.swing.GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE)))
                            .addComponent(lblCompetences))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblName)
                            .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(chkHasParent)
                            .addComponent(cmbParentTheme, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblSubject)
                            .addComponent(cmbSubject, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblCompetences)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 140, Short.MAX_VALUE)
                        .addGap(18, 18, 18))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 248, Short.MAX_VALUE)
                        .addGap(18, 18, 18)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnDelete)
                    .addComponent(btnAdd)
                    .addComponent(btnToSubjects)
                    .addComponent(btnToCompetences)
                    .addComponent(btnToMain)
                    .addComponent(btnSave))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_btnDeleteActionPerformed

    private void chkHasParentActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkHasParentActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_chkHasParentActionPerformed

    private void lstAllThemesValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_lstAllThemesValueChanged
        if (lstAllThemes.getSelectedIndex() != -1) {
            String data = lstAllThemes.getSelectedValue().toString();
            Theme r  = m_model.resource(Themes.class)
                                            .fetch(data);
            m_theme = r;
            updateWidgetsDueAChangedSelection();
        } else {
            m_theme = null;
        }
    }//GEN-LAST:event_lstAllThemesValueChanged

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnSave;
    private javax.swing.JButton btnToCompetences;
    private javax.swing.JButton btnToMain;
    private javax.swing.JButton btnToSubjects;
    private javax.swing.JCheckBox chkHasParent;
    private javax.swing.JComboBox cmbParentTheme;
    private javax.swing.JComboBox cmbSubject;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lblCompetences;
    private javax.swing.JLabel lblName;
    private javax.swing.JLabel lblSubject;
    private javax.swing.JList lstAllThemes;
    private javax.swing.JList lstCompetences;
    private javax.swing.JTextField txtName;
    // End of variables declaration//GEN-END:variables
}
